/**
*@note Copyright 2012-2022 CETHIK All Rights Reserved.
*@brief  用来发布以显示的功能实现类文件
*@author tuyinan
*@data 2022-04-xx
*/
#include <costmap_2d/cost_values.h>
#include <costmap_2d/costmap_2d_publisher.h>

#include <boost/bind.hpp>

namespace costmap_2d {

char* Costmap2DPublisher::cost_translation_table_ = NULL;

Costmap2DPublisher::Costmap2DPublisher(std::string name, Costmap2D* costmap,
                                       ConfigFile* configNode)
    : costmap_(costmap), global_frame_("/map"){
  ros::NodeHandle nh("~/" + name), g_nh;

  always_send_full_costmap_ =
      (*configNode).getValueOfKey<bool>("always_send_full_costmap", true);
  std::string costmap_topic_name =
      (*configNode).getValueOfKeyAsString("costmap_topic_name", "/costmap");
  std::string footprint_topic_name =
      (*configNode).getValueOfKeyAsString("footprint_topic_name", "/footprint");

  costmap_pub_ = nh.advertise<nav_msgs::OccupancyGrid>(
      costmap_topic_name, 1,
      boost::bind(&Costmap2DPublisher::onNewSubscription, this, _1));
  costmap_update_pub_ = nh.advertise<map_msgs::OccupancyGridUpdate>(
      costmap_topic_name + "_updates", 1);
  // todo: 1. publish footprint 2. datacollector 的node部分
  footprint_pub_ =
      nh.advertise<geometry_msgs::PolygonStamped>(footprint_topic_name, 1);

  if (cost_translation_table_ == NULL) {
    cost_translation_table_ = new char[256];

    // special values:
    cost_translation_table_[0] = 0;      // NO obstacle
    cost_translation_table_[253] = 99;   // INSCRIBED obstacle
    cost_translation_table_[254] = 100;  // LETHAL obstacle
    cost_translation_table_[255] = -1;   // UNKNOWN

    // regular cost values scale the range 1 to 252 (inclusive) to fit
    // into 1 to 98 (inclusive).
    for (int i = 1; i < 253; i++) {
      cost_translation_table_[i] = char(1 + (97 * (i - 1)) / 251);
    }
  }

  xn_ = yn_ = 0;
  x0_ = costmap_->getSizeInCellsX();
  y0_ = costmap_->getSizeInCellsY();
}

Costmap2DPublisher::~Costmap2DPublisher() {}

void Costmap2DPublisher::onNewSubscription(
    const ros::SingleSubscriberPublisher& pub) {
  prepareGrid();
  pub.publish(grid_);
}

// prepare grid_ message for publication.
void Costmap2DPublisher::prepareGrid() {
  boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
  double resolution = costmap_->getResolution();

  grid_.header.frame_id = global_frame_;
  grid_.header.stamp = ros::Time::now();
  grid_.info.resolution = resolution;

  grid_.info.width = costmap_->getSizeInCellsX();
  grid_.info.height = costmap_->getSizeInCellsY();

  double wx, wy;
  costmap_->mapToWorld(0, 0, wx, wy);
  grid_.info.origin.position.x = wx - resolution / 2;
  grid_.info.origin.position.y = wy - resolution / 2;
  grid_.info.origin.position.z = 0.0;
  grid_.info.origin.orientation.w = 1.0;
  saved_origin_x_ = costmap_->getOriginX();
  saved_origin_y_ = costmap_->getOriginY();

  grid_.data.resize(grid_.info.width * grid_.info.height);

  unsigned char* data = costmap_->getCharMap();
  for (unsigned int i = 0; i < grid_.data.size(); i++) {
    grid_.data[i] = cost_translation_table_[data[i]];
  }
}

void Costmap2DPublisher::publishCostmap() {
  //   这个技巧可以记一下
  if (costmap_pub_.getNumSubscribers() == 0) {
    // No subscribers, so why do any work?
    return;
  }

  boost::unique_lock<Costmap2D::mutex_t> lock(*(costmap_->getMutex()));
  float resolution = costmap_->getResolution();

  if (always_send_full_costmap_ || grid_.info.resolution != resolution ||
      grid_.info.width != costmap_->getSizeInCellsX() ||
      grid_.info.height != costmap_->getSizeInCellsY() ||
      saved_origin_x_ != costmap_->getOriginX() ||
      saved_origin_y_ != costmap_->getOriginY()) {
    prepareGrid();
    costmap_pub_.publish(grid_);
  } else if (x0_ < xn_) {
    // Publish Just an Update
    map_msgs::OccupancyGridUpdate update;
    update.header.stamp = ros::Time::now();
    update.header.frame_id = global_frame_;
    update.x = x0_;
    update.y = y0_;
    update.width = xn_ - x0_;
    update.height = yn_ - y0_;
    update.data.resize(update.width * update.height);

    unsigned int i = 0;
    for (unsigned int y = y0_; y < yn_; y++) {
      for (unsigned int x = x0_; x < xn_; x++) {
        unsigned char cost = costmap_->getCost(x, y);
        update.data[i++] = cost_translation_table_[cost];
      }
    }
    costmap_update_pub_.publish(update);
  }

  xn_ = yn_ = 0;
  x0_ = costmap_->getSizeInCellsX();
  y0_ = costmap_->getSizeInCellsY();
}

void Costmap2DPublisher::publishFootprint(
    double x, double y, double yaw,
    std::vector<costmap_2d::Point> padded_footprint_) {
  std::vector<costmap_2d::Point> footprint;
  costmap_2d::transformFootprint(x, y, yaw, padded_footprint_, footprint);
  geometry_msgs::PolygonStamped polygon;
  polygon.header.frame_id = global_frame_;
  polygon.header.stamp = ros::Time::now();
  for (int i = 0; i < footprint.size(); i++) {
    geometry_msgs::Point32 pt;
    pt.x = footprint.at(i).x;
    pt.y = footprint.at(i).y;
    polygon.polygon.points.push_back(pt);
  }
  footprint_pub_.publish(polygon);
}
}  // end namespace costmap_2d
